﻿using BGYMqttServer.Handlers;
using BGYMqttServer.Models;
using Core.Web;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace BGYMqttServer.Controllers.Api.v1
{
    /// <summary>
    /// 门口机接口
    /// </summary>
    public class EquipmentsController : ApiController
    {
        /// <summary>
        /// mqtt服务
        /// </summary>
        private readonly MqttMessageHandler mqttService;

        /// <summary>
        /// 门口机接口
        /// </summary>
        /// <param name="mqttService"></param>
        public EquipmentsController(MqttMessageHandler mqttService)
        {
            this.mqttService = mqttService;
        }

        /// <summary>
        /// 查询电梯状态
        /// </summary>
        /// <param name="id">门口机id</param>
        /// <param name="timeout">超时秒数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<StatusBody> QueryStatusAsync(string id, int timeout = 10)
        {
            var request = new MqttMessage<QueryBody>
            {
                Api = MqttApi.Query,
                Body = new QueryBody { CallerId = MqttMessageHandler.ClientId },
                Id = MqttMessage.CreateId(),
                Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            };

            var message = await this.mqttService.SendAsync<QueryBody, StatusBody>(id, request, TimeSpan.FromSeconds(timeout));
            return message.Body;
        }

        /// <summary>
        /// 呼叫电梯
        /// </summary>
        /// <param name="id">门口机id</param>
        /// <param name="floor">目标楼层</param>
        /// <param name="timeout">超时秒数</param>
        /// <returns></returns>
        [HttpPost("{id}/floors/{floor}")]
        public async Task<StatusBody> CallAsync(string id, int floor, int timeout = 10)
        {
            var request = new MqttMessage<CallBody>
            {
                Api = MqttApi.Call,
                Body = new CallBody { CallerId = MqttMessageHandler.ClientId, TargetFloor = floor },
                Id = MqttMessage.CreateId(),
                Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            };

            var message = await this.mqttService.SendAsync<CallBody, StatusBody>(id, request, TimeSpan.FromSeconds(timeout));
            return message.Body;
        }
    }
}
